﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Linq;
using OctoOS;
using OctoOS.UI;
using System.Text;
using System.Web.UI.WebControls;
using System.Net.Mail;
using System.Net;

public partial class item : OOSPage
{
	class PathInfo
	{
		[PathInfoMember(0)]
		internal long adID;

        [PathInfoMember(1, true)]
        internal long categoryID;
	}

	PathInfo _pathInfo;
    Category _category = null;
    ClassifiedAd _ad = null;
    Resource _resource = null;
    List<AttributeValueEntity> _attrValues = new List<AttributeValueEntity>();
    List<AttributeValueEntity> _attrCustomValues = new List<AttributeValueEntity>();


	protected void Page_Init(object sender, EventArgs e)
	{
		_pathInfo = EnablePathInfo<PathInfo>();

        _resource = DataSource.ClassifiedResources_Get(
            OOSRequest.Current.ResourceID);

        if (_pathInfo.adID != 0)
        {
            if (!OOSRequest.Current.IsAuthenticated)
            {
                OOSRequest.Current.EnsureSignIn();
            }
        }
        else
        {
            if (!_resource.AllowAnonAds && !OOSRequest.Current.IsAuthenticated)
            {
                OOSRequest.Current.EnsureSignIn();
            }
        }

         if (_pathInfo.adID == 0 && _pathInfo.categoryID == 0)
        {
            throw new HttpException(404, "The page doesnt exist");
        }
        else
        {
            Helper.Categories.UpdateCategoryCache();

            _ad = DataSource.ClassifiedAds_GetByID(
                    OOSRequest.Current.ResourceID,
                    _pathInfo.categoryID,
                    _pathInfo.adID);

        // attributes
        foreach (var attribute in _ad.Attributes)
        {
            FormRow row = new FormRow();
            row.ID = "RowAttr_" + attribute.ID;
            row.Label = attribute.Title;
            row.Description = attribute.Description;
            if (!attribute.IsCustom)
            {
                row.ID = "RowAttr_" + attribute.ID;
                if (attribute.Required)
                {
                    row.Required = attribute.Required;
                    row.ServerValidate += new EventHandler<ValidateEventArgs>(DDLValidate);
                }
                var ctl = new DropDownList();
                ctl.ID = "DDL_" + attribute.ID;

                // insert default item
                ListItem defItem = new ListItem();
                defItem.Text = "No value";
                defItem.Value = "0";
                ctl.Items.Add(defItem);
                //insert other items
                foreach (var value in attribute.AttributeValues)
                {
                    ListItem item = new ListItem();
                    item.Text = value.AttributeValueName;
                    item.Value = value.AttributeValue.ToString();
                    item.Selected = value.Selected;
                    ctl.Items.Add(item);
                }
                row.Controls.Add(ctl);
            }
            // inserting custom attribute
            else
            {
                row.ID = "RowCustAttr_" + attribute.ID;
                var ctl = new InputText();
                ctl.ID = "text_" + attribute.ID;
                ctl.MaxLength = 100;
                if (attribute.Required)
                {
                    row.Required = attribute.Required;
                    row.ServerValidate += new EventHandler<ValidateEventArgs>(TextValidate);
                }
                ctl.Text = attribute.AttributeValues.Count() == 0 ? "" : attribute.AttributeValues[0].AttributeValueName;
                row.Controls.Add(ctl);
            }

            FormView.Controls.Add(row);
        }

        FormRow submitRow = new FormRow();
        submitRow.ID = "RowSubmit";
        Submit submit = new Submit();
        submit.ID = "submit";
        submit.Click += new EventHandler(OnSubmitClick);
        submitRow.Controls.Add(submit);
        FormView.Controls.Add(submitRow);
         }
    }
   

	protected void Page_Load(object sender, EventArgs e)
	{
       
        if (_ad != null)
        {
            if (_ad.CategoryID != 0)
            {
                _category = Helper.Categories.GetCategory(_ad.CategoryID);
            }
            else
            {
                _category = Helper.Categories.GetCategory(_pathInfo.categoryID);
            }

            if (_category != null)
            {
                RowTitle.Description = "e.g. " + _category.AdNameExample;
            }

            if (_pathInfo.adID > 0 && (DateTime.Today - _ad.PostTime.Date).Days >= 3)
            {
                if ((_ad.UserID != 0 && _ad.UserID == OOSRequest.Current.UserID) || OOSRequest.Current.IsModerator)
                {
                    AddAction("Renew ad", Urls.Classifieds.GetAdRenew(_ad.ID, (DateTime.Today - _ad.PostTime.Date).Days));
                }
            }

            CurrencyText.Text = _ad.CurrencyCode;

            if (_pathInfo.adID != 0)
            {
                if (!IsPostBack)
                {
                    Title.Text = _ad.Title;
                    ExpDate.Value = _ad.ExpiryTime;
                    Searching.SelectedIndex = _ad.Searching ? 1 : 0;
                    AdText.Text = _ad.AdText;
                    Latitude.Value = _ad.Latitude;
                    Longitude.Value = _ad.Longitude;
                    PriceList.SelectedValue = _ad.PriceType.ToString();
                    Price.Value = _ad.Price;

                    Phone.Text = _ad.ContactPhone;
                    Email.Text = _ad.ContactEMail;
                    Url.Text = _ad.ContactUrl;
                }
            }
                

            // setting expdate
            if (_pathInfo.adID == 0)
            {
                PageTitle = "Add New Ad";
                if (OOSRequest.Current.IsAuthenticated)
                {
                    ExpDate.Max = DateTime.Today.AddDays(_ad.ExpNonAnonDays);
                    if (!IsPostBack)
                    {
                        ExpDate.Value = ExpDate.Max;
                    }
                }
                else
                {
                    ExpDate.Max = DateTime.Today.AddDays(_ad.ExpAnonDays);
                    if (!IsPostBack)
                    {
                        ExpDate.Value = ExpDate.Max;
                    }
                }
                ExpDate.Min = DateTime.Today.AddDays(1);
            }
            else
            {
                PageTitle = "Edit Ad";
                if (!IsPostBack)
                {
                    ExpDate.Value = ExpDate.Max = _ad.ExpiryTime;
                }
                ExpDate.Min = DateTime.Today.AddDays(1);
                if (OOSRequest.Current.IsAuthenticated)
                {
                    ExpDate.Max = _ad.PostTime.AddDays(_ad.ExpNonAnonDays);
                }
                else
                {
                    ExpDate.Max = _ad.PostTime.AddDays(_ad.ExpAnonDays);
                }
            }
            SetBreadcrumbs();
        }
        else
        {
            throw new HttpException(404, "The page isn't exist");
        }
	}

    private void SetBreadcrumbs()
    {
        Category[] _allCategories = Helper.Categories.GetAllCategories();

        AddBreadcrumb(string.Empty, "/");

        long categoryID = _pathInfo.categoryID == 0 ? _ad.CategoryID : _pathInfo.categoryID;

        Category parentCategory = Helper.Categories.GetParentCategory(categoryID);
        Category grandParentCategory = Helper.Categories.GetGrandParentCategory(categoryID);
        Category currentCategory = Helper.Categories.GetCategory(categoryID);
        if (currentCategory != null)
        {
            //RowTitle.Description = currentCategory.AdNameExample;

            if (grandParentCategory != null)
            {
                AddBreadcrumb(grandParentCategory.Name, Urls.Classifieds.GetCategoryInfo(grandParentCategory.ID));
            }
            if (parentCategory != null)
            {
                AddBreadcrumb(parentCategory.Name, Urls.Classifieds.GetCategoryInfo(parentCategory.ID));
            }
            if (currentCategory != null)
            {
                AddBreadcrumb(currentCategory.Name, Urls.Classifieds.GetCategoryInfo(currentCategory.ID));
            }
        }
    }

    protected void OnSubmitClick(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            byte status;
            if (_ad.NeedToApprove)
            {
                status = (byte)Helper.AdStatus.Pending;
            }
            else
            {
                status = (byte)Helper.AdStatus.Active;
            }
            Encoding encoding = new ASCIIEncoding();
            DataSource.ClassifiedAds_Save(
                OOSRequest.Current.ResourceID,
                _pathInfo.categoryID,
                _pathInfo.adID == 0 ? OOSRequest.Current.RequestID : _pathInfo.adID,
                Title.TrimmedText,
                AdText.TrimmedText,
                ExpDate.Value,
                0,//textFormat
                Searching.SelectedIndex == 1,
                Double.IsNaN(Latitude.Value) ? 0 : Latitude.Value,
                Double.IsNaN(Longitude.Value) ? 0 : Longitude.Value,
                Convert.ToByte(PriceList.SelectedValue),
                Double.IsNaN(Price.Value) ? 0 : Price.Value,
                Phone.TrimmedText,
                Email.TrimmedText,
                Url.TrimmedText,
                OOSRequest.Current.UserID,
                0, //userComputerID,
                encoding.GetBytes(OOSRequest.Current._UserIP),
                GetAttributeValues(),
                GetCustomAttributeValues(),
                status);

            if (status == (byte)Helper.AdStatus.Pending)
            {
                SendMailToAdmin();
            }

            if (OOSRequest.Current.UserID==0)
            {
                if (_pathInfo.categoryID == 0)
                {
                    Response.Redirect(Urls.Classifieds.GetCategoryInfo(_ad.CategoryID));
                }
                else
                {
                    Response.Redirect(Urls.Classifieds.GetCategoryInfo(_pathInfo.categoryID));
                }
            }
            else
            {
                if (_ad.NeedToApprove)
                {
                    Response.Redirect(Urls.Classifieds.GetMyAds(Searching.SelectedIndex == 0 ? (byte)Helper.AdType.Offer : (byte)Helper.AdType.Need, (byte)Helper.AdStatus.Pending));
                }
                else
                {
                    Response.Redirect(Urls.Classifieds.GetMyAds(Searching.SelectedIndex == 0 ? (byte)Helper.AdType.Offer : (byte)Helper.AdType.Need, (byte)Helper.AdStatus.Active));
                }
            }
        }
    }

    private void SendMailToAdmin()
    {
        if (!String.IsNullOrEmpty(_resource.AdminMail))
        {
            try
            {
                MailMessage message = new MailMessage();
                message.From = new MailAddress("dim17@yandex.ru");
                message.To.Add(new MailAddress(_resource.AdminMail));
                message.Subject = "New Ad To Approve";
                message.Body = "You have a new ad to approve:\n\n";
                message.Body += "http://"+OOSRequest.Current.DomainName+"/myApp/"+Urls.Classifieds.GetAdApprove(_pathInfo.adID == 0 ? OOSRequest.Current.RequestID : _pathInfo.adID);
                SmtpClient client = new SmtpClient();
                client.Host = "smtp.yandex.ru";
                NetworkCredential basicCrenntial = new NetworkCredential("dim17", "buford");
                client.UseDefaultCredentials = false;
                client.Credentials = basicCrenntial;
                client.Send(message);
            }
            catch (Exception ex)
            {
            }
        }
    }

    protected void DDLValidate(object sender, ValidateEventArgs e)
    {
        foreach (var ctl in ((FormRow)sender).Controls)
        {
            if (ctl is DropDownList)
            {
                if (((DropDownList)ctl).SelectedIndex == 0)
                {
                    e.ErrorMessage = "You have to select a value";
                    break;
                }
            }
        }
    }

    protected void TextValidate(object sender, ValidateEventArgs e)
    {
        foreach (var ctl in ((FormRow)sender).Controls)
        {
            if (ctl is InputText)
            {
                if (((InputText)ctl).TrimmedText == "")
                {
                    e.ErrorMessage = "You have to write a message here";
                    break;
                }
            }
        }
    }

    private AttributeValueEntity[] GetAttributeValues()
    {
        List<AttributeValueEntity> list = new List<AttributeValueEntity>();
        foreach (var row in FormView.Controls)
        {
            if ((row is FormRow) && (row as FormRow).ID.ToLower().Contains("rowattr_"))
            {
                foreach (var ddl in (row as FormRow).Controls)
                {
                    if (ddl is DropDownList && (ddl as DropDownList).SelectedIndex>0)
                    {
                        list.Add(
                            new AttributeValueEntity(
                                Convert.ToInt64((ddl as DropDownList).ID.Substring(4)),
                                Convert.ToByte((ddl as DropDownList).SelectedValue),
                                ""));
                    }
                }
            }
        }

        return list.ToArray();
    }

    private AttributeValueEntity[] GetCustomAttributeValues()
    {
        List<AttributeValueEntity> list = new List<AttributeValueEntity>();
        foreach (var row in FormView.Controls)
        {
            if ((row is FormRow) && (row as FormRow).ID.ToLower().Contains("rowcustattr_"))
            {
                foreach (var ddl in (row as FormRow).Controls)
                {
                    if (ddl is InputText && (ddl as InputText).TrimmedText != "")
                    {
                        list.Add(
                            new AttributeValueEntity(
                                Convert.ToInt64((ddl as InputText).ID.Substring(5)),
                                0,
                                (ddl as InputText).TrimmedText));
                    }
                }
            }
        }
        return list.ToArray();
    }
}